package com.yadang.infra.utils;


import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

public class XMLUtils {
    /**
     * 通过XPath表达式从XML字符串中获取特定路径的元素值。
     *
     * @param xmlContent XML内容的字符串表示
     * @param xpathExpression 要评估的XPath表达式
     * @return 评估XPath表达式后的结果字符串，如果不成功则返回null
     */
    public static String getElementValueByXPath(String xmlContent, String xpathExpression) {
        try {
            // 创建Document对象，以便处理XML
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new java.io.ByteArrayInputStream(xmlContent.getBytes()));

            // 创建XPath对象
            XPathFactory xpathFactory = XPathFactory.newInstance();
            XPath xpath = xpathFactory.newXPath();

            // 编译XPath表达式
            XPathExpression expr = xpath.compile(xpathExpression);

            // 执行XPath表达式，并获取结果

            return (String) expr.evaluate(document, XPathConstants.STRING);

        } catch (Exception e) {
            throw new RuntimeException();
        }

    }

    public static void main(String[] args) {
        // 一个示例的XML内容
        String xmlContent = "<service><body><source>YourValue</source></body></service>";
        // XPath表达式，获取/service/body/source元素内的文本
        String xpathExpression = "/service/body/source";

        String value = XMLUtils.getElementValueByXPath(xmlContent, xpathExpression);
        if (value != null) {
            System.out.println("The value of the element is: " + value);
        } else {
            System.out.println("Element not found or error in XML processing.");
        }
    }
}